<template>
  <a-spin :spinning="loading" :tip="tip">
    <div class="container">
      <webview
        v-if="printSrc"
        id="printWebViewRef"
        ref="printWebViewRef"
        :src="printSrc"
        style="display: inline-flex; width: 52rem; height: 65vh"
      ></webview>
      <webview
        v-if="printSrc2"
        id="printWebViewRef2"
        ref="printWebViewRef2"
        :src="printSrc2"
        style="display: none; width: 800px; height: 500px"
      ></webview>
      <webview
        v-if="printSrc3"
        id="printWebViewRef3"
        ref="printWebViewRef3"
        :src="printSrc3"
        style="display: none; width: 800px; height: 500px"
      ></webview>
      <webview
        v-if="printSrc4"
        id="printWebViewRef4"
        ref="printWebViewRef4"
        :src="printSrc4"
        style="display: none; width: 800px; height: 500px"
      ></webview>
      <div class="hd-print">
        <a-button @click="close" class="button"> 返回 </a-button>
        <a-button @click="print" class="button"> 打印页面 </a-button>
      </div>
      <a-modal
        title="提示"
        :visible="visible"
        @ok="handleOk"
        @cancel="handleCancel"
        ok-text="确认"
        cancel-text="取消"
      >
        <p>{{ modalTips }}</p>
      </a-modal>
      <a-modal
        title="提示"
        :visible="visible2"
        @ok="handleOk2"
        @cancel="handleCancel2"
        ok-text="确认"
        cancel-text="取消"
      >
        <p>{{ modalTips2 }}</p>
      </a-modal>
      <a-modal
        type="info"
        title="提示"
        :closable="false"
        :visible="percentVisible"
      >
        <center>
          <p>{{ modalTips3 }}</p>
          <a-progress
            v-show="percentVisible"
            type="circle"
            :percent="percent"
          />
        </center>
        <template slot="footer">
          <a-button>知道了</a-button>
        </template>
      </a-modal>
    </div>
  </a-spin>
</template>

<script>
import {
  printOrder,
  checkPrinter,
  getPrinterList,
  getPrinterInfo,
  printAttachment,
} from "@/api/main";
const ORDER_TYPE_TRANS = 0;
const ORDER_TYPE_ATTACHMENT = 1;

const PRINTER_STATUS_PROCESSING_ATTACHMENT_MSG = "附件打印中";

const PAGE_LOADING_MSG = "打印页面加载中......";
const PAGE_LOADED_MSG = "打印页面加载完成";

const DEFAULT_PRINTER_NAME = "运输单打印机";

const PRINTER_STATUS_READY = "ready";
const PRINTER_STATUS_READY_MSG = "打印机已就绪";

const PRINTER_STATUS_PROCESSING = "processing";
const PRINTER_STATUS_PROCESSING_MSG = "打印机打印中";

const PRINTER_STATUS_INIT = "initializing";
const PRINTER_STATUS_INIT_MSG = "打印机初始化中，请稍等！";

const PRINTER_STATUS_CLOSE_DOOR = "trayEmptyOrOpen";
const PRINTER_STATUS_CLOSE_DOOR_MSG =
  "打印机缺纸或者打印机门打开，请联系管理员！";

const PRINTER_STATUS_IN_SAVE_POWER = "inPowerSave";
const PRINTER_STATUS_IN_SAVE_POWER_MSG = "打印机处于节能模式，请联系管理员！";

const PRINT_STATUS_ERROR_MSG = "打印机状态错误，请联系管理员！！";
const PRINT_FINISHED_MSG = "打印完成，确认点击返回首页！";
const ATTACHMENT_PRINT_FINISHED_MSG = "附件打印成功";

const FAILED_MSG = "单据异常，请联系发运员。";

export default {
  name: "PrintInfo",
  data() {
    return {
      modalTips3: "正在处理数据，请勿动关闭....",
      percentVisible: false,
      percent: 0,
      tip: "",
      visible: false,
      visible2: false,
      modalTips: "",
      modalTips2: "",
      loading: false,
      printSrc: "",
      printSrc2: "",
      printSrc3: "",
      printSrc4: "",
      printerInfo: {},
      printFinished: false,
    };
  },
  mounted() {
    if (this.$route.params.orderId && this.$route.params.shipOrderId) {
      this.orderId = this.$route.params.orderId;
      this.printSrc =
        process.env.VUE_APP_API_BASE_URL +
        "/print?shipOrderId=" +
        this.$route.params.shipOrderId +
        "&orderId=" +
        this.orderId +
        "&status=0&authorization=Basic%20aGRjcV9wZGEwMTo4NzBlODhkODAwOGY0NTI2OGQ2MTg0NGYzNzIwOWI2OQ==3";
      console.log(this.printSrc);
      this.printSrc2 = this.printSrc + "&page=二";
      this.printSrc3 = this.printSrc + "&page=三";
      this.printSrc4 = this.printSrc + "&page=四";

      this.loadPageIntervel = setInterval(() => {
        if (
          this.$refs.printWebViewRef.isLoading() ||
          this.$refs.printWebViewRef2.isLoading() ||
          this.$refs.printWebViewRef3.isLoading() ||
          this.$refs.printWebViewRef4.isLoading()
        ) {
          this.tip = PAGE_LOADING_MSG;
          this.loading = true;
        } else {
          clearInterval(this.loadPageIntervel);
          this.tip = PAGE_LOADED_MSG;
          this.loading = false;
        }
      }, 1000);
      this.timrOuter = setTimeout(() => {
        clearInterval(this.loadingInterval);
        clearTimeout(this.timrOuter);
      }, 20000);
      this.printOrderList = JSON.parse(localStorage.getItem("printOrderList"));
      this.printOrderTypeList = this.printOrderList.filter(
        (item) => item.orderType == ORDER_TYPE_TRANS
      );
      this.printAttachmentTypeList = this.printOrderList.filter(
        (item) => item.orderType == ORDER_TYPE_ATTACHMENT
      );
    } else {
      this.goBack();
    }
  },
  beforeDestroy() {
    console.log("beforeDestroy");
    clearInterval(this.loadingInterval);
    clearInterval(this.progressInterval);
  },
  methods: {
    goBack() {
      this.$router.replace({
        name: "Welcome",
      });
    },
    handleOk() {
      this.visible = false;
      if (this.printFinished) {
        this.goBack();
      }
    },
    handleCancel() {
      this.visible = false;
      if (this.printFinished) {
        this.goBack();
      }
    },
    handleOk2() {
      this.visible2 = false;
      this.visible = true;
    },
    handleCancel2() {
      this.goBack();
      this.visible2 = false;
    },

    close() {
      this.goBack();
    },
    sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    },
    async check() {
      let showErrorInfo = localStorage.getItem("showErrorInfo");
      if (!showErrorInfo) {
        showErrorInfo = true;
      }
      try {
        this.percentVisible = true;
        this.percent = 10;
        this.percentInterval = setInterval(() => {
          this.percent = this.percent + 1;
          console.log(this.percent);
          if (this.percent == 95) {
            this.percent = 20;
          }
        }, 100);

        const res = await printOrder({
          shipOrderId: this.$route.params.shipOrderId,
        });

        if (res && res.success) {
          this.esbInfo = res.data.EsbInfo;
          if (this.esbInfo.returnStatus == "E") {
            this.percentVisible = false;
            if (showErrorInfo) {
              this.modalTips = FAILED_MSG + this.esbInfo.returnMsg;
            } else {
              this.modalTips = FAILED_MSG + "返回的错误信息为空！";
            }
            this.visible = true;
            return false;
          } else if (this.esbInfo.returnStatus == "S") {
            this.percent = 100;
            this.modalTips3 = "处理完成！";
            this.percentVisible = false;
            return true;
          }
        }
      } catch (error) {
        this.loading = false;
        console.log("error:" + JSON.stringify(error));
        this.modalTips = FAILED_MSG + JSON.stringify(error);
        return false;
      } finally {
        clearInterval(this.percentInterval);
      }
    },
    async checkPrinter() {
      let flag = false;
      this.tip = "检测打印机中...";
      this.loading = true;
      try {
        const res = await getPrinterList();
        if (res && res.success) {
          if (res.data.printers && res.data.printers.length > 0) {
            this.printerInfo = res.data.printers.find((printer) => {
              return printer.printerName == DEFAULT_PRINTER_NAME;
            });
            if (this.printerInfo) {
              if (this.printerInfo.online) {
                const resStatus = await checkPrinter(this.printerInfo.portName);
                if (
                  resStatus &&
                  resStatus.success &&
                  resStatus.data.code != 1000
                ) {
                  this.printerStatus = resStatus.data;
                  if (this.printerStatus[0].Status == PRINTER_STATUS_READY) {
                    this.tip = PRINTER_STATUS_READY_MSG;
                    flag = true;
                  } else if (
                    this.printerStatus[0].Status == PRINTER_STATUS_INIT
                  ) {
                    this.modalTips = PRINTER_STATUS_INIT_MSG;
                    this.visible = true;
                  } else if (
                    this.printerStatus[0].Status == PRINTER_STATUS_PROCESSING
                  ) {
                    this.modalTips = PRINTER_STATUS_PROCESSING_MSG;
                  } else if (
                    this.printerStatus[0].Status == PRINTER_STATUS_CLOSE_DOOR
                  ) {
                    this.modalTips = PRINTER_STATUS_CLOSE_DOOR_MSG;
                    this.visible = true;
                  } else if (
                    this.printerStatus[0].Status == PRINTER_STATUS_IN_SAVE_POWER
                  ) {
                    flag = true;
                    // this.modalTips = "打印机节电模式，请唤醒！";
                    // this.visible = true;
                  }
                } else {
                  this.modalTips = PRINT_STATUS_ERROR_MSG;
                  this.visible = true;
                }
              } else {
                this.modalTips =
                  DEFAULT_PRINTER_NAME + "打印机不在线，请联系管理员！";
                this.visible = true;
              }
            } else {
              this.modalTips =
                "打印机名称未设置为" +
                DEFAULT_PRINTER_NAME +
                "，找不到打印机，请联系管理员！";
              this.visible = true;
            }
          } else {
            this.modalTips = "打印机sdk未安装，找不到打印机，请联系管理员！";
            this.visible = true;
          }
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
        return flag;
      }
    },
    async checkPrinterFinished() {
      let flag = false;
      try {
        const res = await getPrinterList();
        if (res && res.success) {
          if (res.data.printers && res.data.printers.length > 0) {
            this.printerInfo = res.data.printers.find((printer) => {
              return printer.printerName == DEFAULT_PRINTER_NAME;
            });
            if (this.printerInfo) {
              if (this.printerInfo.online) {
                // this.getPrinerFinishStatus();
                const resUsage = await getPrinterInfo(
                  "usage",
                  this.printerInfo.portName
                );
                this.totalImpressions = resUsage.data.TotalImpressions;
                this.processed = 0;
                this.interval = setInterval(async () => {
                  const status = await this.getPrinterFinishStatus(
                    this.printerInfo.portName
                  );
                  this.timrOuter = setTimeout(() => {
                    clearTimeout(this.timrOuter);
                    clearInterval(this.interval);
                  }, 20000);
                }, 200);
              } else {
                this.modalTips =
                  DEFAULT_PRINTER_NAME + "打印机不在线，请联系管理员！";
                this.visible = true;
              }
            } else {
              this.modalTips =
                "打印机名称未设置为" +
                DEFAULT_PRINTER_NAME +
                "，找不到打印机，请联系管理员！";
              this.visible = true;
            }
          } else {
            this.modalTips = "打印机sdk未安装，找不到打印机，请联系管理员！";
            this.visible = true;
          }
        }
      } catch (error) {
        console.log("获取打印机状态失败，错误：{}", error);
      } finally {
        clearTimeout(this.timrOuter);
        clearInterval(this.interval);
        this.loading = false;
        return flag;
      }
    },
    async getPrinterFinishStatus(portName) {
      const resStatus = await checkPrinter(portName);
      if (resStatus && resStatus.success && resStatus.data.code != 1000) {
        this.printerStatus = resStatus.data;
        console.log("nowStatus:" + this.printerStatus[0].Status);
        if (this.printerStatus[0].Status == PRINTER_STATUS_READY) {
          this.tip = PRINTER_STATUS_READY_MSG;
          if (this.processed > 0) {
            clearInterval(this.interval);
            this.tip = PRINT_FINISHED_MSG;
            this.modalTips = this.tip;
            this.printFinished = true;
            this.loading = false;
            this.visible = true;
          }
        } else if (this.printerStatus[0].Status == PRINTER_STATUS_INIT) {
          this.tip = PRINTER_STATUS_INIT_MSG;
        } else if (this.printerStatus[0].Status == PRINTER_STATUS_PROCESSING) {
          this.processed++;
          this.tip = PRINTER_STATUS_PROCESSING_MSG;
        } else if (this.printerStatus[0].Status == PRINTER_STATUS_CLOSE_DOOR) {
          clearInterval(this.interval);
          this.tip =
            PRINTER_STATUS_CLOSE_DOOR_MSG + PRINTER_STATUS_PROCESSING_MSG;
          this.loading = false;
          this.modalTips2 =
            this.tip +
            "如果打印完，请点击确定，未打印完成联系管理员添加纸张后,点击取消继续打印！";
          this.modalTips = this.tip + "添加纸张后，点击确认！";
          this.visible2 = true;
        } else if (
          this.printerStatus[0].Status == PRINTER_STATUS_IN_SAVE_POWER
        ) {
          this.tip =
            PRINT_FINISHED_MSG + ",共打印" + this.finishImpressions + "页!";
          this.modalTips = this.tip;
          this.loading = false;
          this.visible = true;
          this.printFinished = true;
        } else {
          clearInterval(this.interval);
          this.modalTips = PRINT_STATUS_ERROR_MSG;
          this.loading = false;
          this.visible = true;
        }
      } else {
        clearInterval(this.interval);
        this.modalTips = "获取打印机状态失败，请联系管理员！";
        this.loading = false;
        this.visible = true;
      }
    },
    async showPrintInfo(modalTips) {
      return new Promise((resolve, reject) => {
        this.$confirm({
          cancelText: "取消",
          okText: "确定",
          title: "提示",
          icon: "info-circle",
          content: modalTips,
          onOk() {
            resolve(true);
          },
          onCancel() {
            resolve(false);
          },
        });
      }).catch((err) => {
        console.log(err);
      });
    },
    async ptintOrderList(haveAttachment) {
      this.loading = true;
      this.tip = "打印第一页，共三页...";
      const printObj = document.querySelector("#printWebViewRef");
      try {
        printObj.print({
          silent: true,
          printBackground: true,
          //打印机的名称，就是本文一开始获得的打印机列表其中一个
          deviceName: DEFAULT_PRINTER_NAME,
          footer: false,
          header: false,
        });
        await this.checkPrinterFinished();
        this.loading = true;
        this.tip = "打印第二页，共三页...";
        const printObj2 = document.querySelector("#printWebViewRef2");
        printObj2.print({
          silent: true,
          printBackground: true,
          //打印机的名称，就是本文一开始获得的打印机列表其中一个
          deviceName: DEFAULT_PRINTER_NAME,
          footer: false,
          header: false,
        });
        await this.checkPrinterFinished();

        this.loading = true;
        this.tip = "打印第三页，共三页...";
        const printObj3 = document.querySelector("#printWebViewRef3");
        printObj3.print({
          silent: true,
          printBackground: true,
          //打印机的名称，就是本文一开始获得的打印机列表其中一个
          deviceName: DEFAULT_PRINTER_NAME,
          footer: false,
          header: false,
        });
        this.loading = true;
        this.tip = "打印第4页，共4页...";
        const printObj4 = document.querySelector("#printWebViewRef4");
        printObj4.print({
          silent: true,
          printBackground: true,
          //打印机的名称，就是本文一开始获得的打印机列表其中一个
          deviceName: DEFAULT_PRINTER_NAME,
          footer: false,
          header: false,
        });
        await this.checkPrinterFinished();
      } catch (error) {
        console.log(error);
      } finally {
        clearInterval(this.interval);
        this.tip = PRINT_FINISHED_MSG;
        this.loading = false;
        if (!haveAttachment) {
          this.modalTips = this.tip;
          this.printFinished = true;
          this.visible = true;
        }
      }
    },

    async print() {
      let modalTips = `将打印运单${this.printOrderTypeList.length}个和附件${this.printAttachmentTypeList.length}个！`;
      const ok = await this.showPrintInfo(modalTips);
      if (!ok) {
        return;
      }
      const printerFlag = await this.checkPrinter();
      if (!printerFlag) {
        return;
      }

      try {
        const checkFlag = await this.check();
        if (!checkFlag) {
          return;
        }
        if (this.printOrderTypeList.length > 0) {
          console.log("打印运单：", this.printOrderTypeList);
          await this.ptintOrderList(this.printAttachmentTypeList.length > 0);
        }
      } catch (error) {
        console.log("打印运单错误：", error);
        return;
      }

      if (this.printAttachmentTypeList.length > 0) {
        console.log("打印附件：", this.printAttachmentTypeList);

        this.tip = PRINTER_STATUS_PROCESSING_ATTACHMENT_MSG;
        this.loading = true;
        try {
          const res = await printAttachment(this.printAttachmentTypeList);
          if (res.code == 0) {
            this.tip = ATTACHMENT_PRINT_FINISHED_MSG;
            this.printFinished = true;
            this.modalTips = ATTACHMENT_PRINT_FINISHED_MSG;
            console.log(res.data);
          } else {
            this.modalTips = FAILED_MSG + JSON.stringify(res);
            this.visible = true;
          }
        } catch (error) {
          let modalTips = "打印机在努力打印中，打印完成请点击确认！";
          const okPrint = await this.showPrintInfo(modalTips);
          if (okPrint) {
            this.goBack();
          }
        } finally {
          this.loading = false;
          this.visible = true;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 75vh;
  align-items: center;
  justify-content: flex-start;
  .hd-table {
    border: 1px #000 solid;
  }
  .hd-print {
    display: flex;
    flex-direction: row;
    padding: 1rem 2rem;
    justify-content: space-around;
    position: fixed;
    bottom: 15vh;
  }
}
</style>